package com.xiaoma.base.weakrefence;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;


/**
 * 测试弱引用
 */
public class WeakRefenceDemo {

    static Map<WeakReference<String>, String> map;

    public static void main(String[] args) throws Exception {

        WeakRefenceDemo demo = new WeakRefenceDemo();
        demo.weakTest();
        System.out.println("gc 发生前：" + map.size());
        System.out.println("开始通知GC");
        //注意，这里只是通过垃圾回收器进行垃圾回收，并不一定马上执行
        System.gc();
        Thread.sleep(1000 * 5);
        System.out.println("gc 发生后：" + map.size());


    }


    /**
     * 弱引用测试
     */
    public void weakTest() {
        map = new WeakHashMap<>();
        String key = new String("key");
        String value = new String("value");
        map.put(new WeakReference<>(key), value);
        key = null;
        value = null;

    }

}
